import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { VipInfo } from './vipinfo.entity';
import { Goods } from 'src/goods/goods.entity';
import { Repository, EntityManager } from 'typeorm';
import { DURATION_UNIT } from 'src/common/const/const';
import { GoodsNotFoundError } from 'src/common/utils/error';
import { serviceInfoLog,serviceErrorLog } from "src/common/out/logger/access.logger";

@Injectable()
export class VipInfoService {
    constructor(
        @InjectRepository(VipInfo)
        private vipInfoRepository: Repository<VipInfo>,
        @InjectRepository(Goods)
        private goodsRepository: Repository<Goods>,
    ) { }


    async handleVipInfoAfterPayment(entityManager: EntityManager, userid: string, goodsId: number): Promise<void> {
        serviceInfoLog(`[handleVipInfoAfterPayment] userid: ${userid}, goodsId: ${goodsId}`)

        const goods = await this.goodsRepository.findOne({ where: { id: goodsId } });
        if (!goods) {
            throw new GoodsNotFoundError(goodsId);
        }

        const now = new Date();
        let vipInfo = await this.vipInfoRepository.findOne({ where: { userid } });

        // vipInfo 不存在，新建 vipInfo
        if (!vipInfo) {
            await this.createVipInfo(entityManager, userid, goods, now);
            return;
        }

        // 已经是永久 vip 直接返回
        if (vipInfo.isPermanent) {
            serviceInfoLog(`[handleVipInfoAfterPayment] ${userid} already is permanent vip`);
            return;
        }

        // 更新已有 vipInfo
        await this.updateVipInfo(entityManager, vipInfo, goods, now);
    }

    private async createVipInfo(entityManager: EntityManager, userid: string, goods: any, now: Date): Promise<VipInfo> {
        const endTime = goods.isPermanent ? null : this.calculateEndTime(goods.durationUnit, goods.duration, now);
        const vipInfoData = {
            userid,
            startTime: now,
            endTime: endTime,
            isPermanent: goods.isPermanent
        };

        const vipInfo = entityManager.create(VipInfo, vipInfoData);
        await entityManager.save(VipInfo, vipInfo);
        serviceInfoLog(`[handleVipInfoAfterPayment] create new vip_info, vipInfoData: ${JSON.stringify(vipInfoData, null, 2)}`);
        return vipInfo;
    }

    private calculateEndTime(durationUnit, duration: number, startTime: Date): Date {
        const endTime = new Date(startTime); // 创建一个新的 Date 对象以避免修改原始 startTime

        switch (durationUnit) {
            case DURATION_UNIT.YEAR:
                endTime.setFullYear(endTime.getFullYear() + duration);
                break;
            case DURATION_UNIT.MONTH:
                endTime.setMonth(endTime.getMonth() + duration);
                break;
            case DURATION_UNIT.DAY:
                endTime.setDate(endTime.getDate() + duration);
                break;
            default:
                throw new Error(`Invalid duration unit. Must be ${DURATION_UNIT.YEAR}, ${DURATION_UNIT.MONTH}, or ${DURATION_UNIT.DAY}.`);
        }
        return endTime;
    }

    private async updateVipInfo(entityManager: EntityManager, vipInfo: VipInfo, goods: any, now: Date): Promise<void> {
        vipInfo.endTime = this.calculateNewEndTime(vipInfo.endTime, goods, now);
        vipInfo.isPermanent = goods.isPermanent;

        await entityManager.save(VipInfo, vipInfo);
        serviceInfoLog(`[handleVipInfoAfterPayment] updated vip_info, vipInfo: ${JSON.stringify(vipInfo, null, 2)}`);
    }

    private calculateNewEndTime(currentEndTime: Date | null, goods: any, now: Date): Date | null {
        // 在 vipInfo 已有 endTime 基础上，计算新 endTime
        if (goods.isPermanent) {
            return null;
        }

        if (currentEndTime && currentEndTime > now) { // VIP未过期
            return this.calculateEndTime(goods.durationUnit, goods.duration, currentEndTime);
        } else { // VIP过期
            return this.calculateEndTime(goods.durationUnit, goods.duration, now);
        }
    }

    async isVipUser(userid: string): Promise<boolean> {
        // 查找用户的 VIP 信息
        const vipInfo = await this.vipInfoRepository.findOne({ where: { userid } });
        if (!vipInfo) {
            return false
        }
        if (vipInfo.isPermanent) {
            return true
        }

        // 获取当前时间
        const now = new Date();

        // 判断 VIP 信息是否有效
        if (vipInfo) {
            const isActive = vipInfo.startTime < now &&
                (vipInfo.endTime > now || vipInfo.endTime === null);
            return isActive;
        }
        // 如果没有找到 VIP 信息，则用户不是 VIP
        return false;
    }

}


